<template>
  <div class="container">
    <div class="app-container">
      <el-button class="btn-add" size="mini" type="primary" @click="optionPopout">添加权限</el-button>

      <el-table stripe default-expand-all :data="list" row-key="id">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" type="flex">
          <template v-slot="{ row }">
            <el-button v-if="row.type === 1" size="mini" type="text" @click="sonLocal(row.id)">添加</el-button>
            <el-button size="mini" type="text" @click="updataThispermission(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delPermission(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <Popup ref="sonPopup" v-model="show" :is-add.sync="isAdd" :updata-id.sync="updataId" :add-obj="addObj" @refresh="getPermissionList" />
  </div>
</template>
<script>
import { getPermissionList, delPermission } from '@/api/permission'
import { transListToTreeData } from '@/utils/auth'
import Popup from './components/popup'
export default {
    name: 'Permission',
    components: {
        Popup
    },
    data() {
        return {
            list: [],
            show: false,
            addObj: {
                // 层级
                type: 1,
                // 父级id
                pid: 0
            },
            // 要修改的id
            updataId: -1,
            isAdd: true
        }
    },
    created() {
        this.getPermissionList()
    },
    methods: {
        async getPermissionList() {
            this.list = transListToTreeData(await getPermissionList(), 0) // 将列表数据转化成树形结构
        },
        // 添加0级权限
        optionPopout() {
            this.show = true // 打开弹框
        },
        // 添加1级权限
        sonLocal(id) {
            this.addObj = {
                type: 2,
                pid: id
            }
            this.show = true
        },
        // 修改逻辑
        updataThispermission(id) {
            // 复用弹层组件
            // 传值给弹窗
            this.updataId = id
            this.isAdd = false
            this.$nextTick(async() => {
                // 调用子组件的方法，让其初始化
                await this.$refs.sonPopup.updataThisData()
                // 打开弹窗
                this.show = true
            })
            // 弹层拿到id，当即判断结果，弹层应当对这个值有重置操作
        },
        // 删除逻辑
        async delPermission(id) {
            // 直接调用对应接口
            await delPermission(id)
            this.$message.success('删除成功')
            // 刷新
            this.getPermissionList()
        }
    }
}
</script>
<style>
.btn-add {
  margin: 10px;
}
</style>
